package znbkTestPaperRdqh.fragment;

import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.lancooznbk.R;
import com.example.lancooznbk.utils.DialogHelper;
import com.example.lancooznbk.view.base.BaseFragment;
import com.example.lancooznbk.view.widget.ClickImageView;
import com.example.lancooznbk.view.widget.ScaleButton;
import com.google.gson.Gson;
import com.lancoo.rxretrofitlibrary.Api.UserInfo;

import java.util.ArrayList;
import java.util.List;

import lancooControl.AnswerViewPagerAdapter;
import lancooCustomListview.BounceListView;
import znbkTopicType.WrapBaseAdapter;
import znbkTestPaperBj.entity.NotePaperEntity;
import znbkTestPaperCtfd.activity.WrongTopicTutoringPaperActivity;
import znbkTestPaperCtfd.entity.WrongTopicTutoringModel;
import znbkTestPaperCtfd.entity.WrongTopicTutoringModelEntity;
import znbkTestPaperInfor.ZnbkPaperDef;
import znbkTestPaperInfor.ZnbkPaperInfor;
import znbkTestPaperRdqh.activity.WeekAscensionPaperActivity;
import znbkTopicType.NoteDetailActivity;
import znbkTopicType.content.ZnbkContentDxtAdapter;
import znbkTopicType.content.ZnbkContentPptAdapter;
import znbkTopicType.content.ZnbkContentTktAdapter;
import znbkTopicType.content.ZnbkContentXztAdapter;
import znbkTopicType.content.ZnbkContentZwAdapter;
import znbkTopicType.response.ZnbkResponsePptAdapter;
import znbkTopicType.response.ZnbkResponseTktAdapter;
import znbkTopicType.response.ZnbkResponseXztAdapter;

import static znbkTestPaperRdqh.activity.WeekAscensionPaperActivity.PAPER_FROM;
import static znbkTestPaperRdqh.activity.WeekAscensionPaperActivity.mEntityRdqh;

/**
 * Created by Administrator on 2018\4\2 0002.
 */

public class WeekAscensionPaperFragment extends BaseFragment {
    private int mNum; //页号
    private ArrayList<View> list;
    private TextView TvContentType;//题目简介
    private BounceListView LvContent;//试题主干部分
    private TextView TvContentNumber;//
    public ViewPager VpAnswer;
    private WrapBaseAdapter mAdapter;

    private LinearLayout LayoutSelfRate;
    private int state = 0;//试卷作答状态

    private View relContainer;

    public static int currentSmallViewPage;
    private int layoutId;

    private int mModelFrom;
    private FrameLayout mFlLoading;

    public static boolean IsHaveNoteRdqh = false;
    private TextView mTvTypeName;//题目类型
    private ClickImageView mCivNote;
    private ClickImageView mCivAccessToCounselling;
    private ClickImageView mCivKnowledgePoint;


    public static WeekAscensionPaperFragment newInstance(int num) {
        WeekAscensionPaperFragment fragment = new WeekAscensionPaperFragment();
        // Supply num input as an argument.
        Bundle args = new Bundle();
        args.putInt("num", num);
        fragment.setArguments(args);
        return fragment;
    }



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //这里我只是简单的用num区别标签，其实具体应用中可以使用真实的fragment对象来作为叶片
        mNum = getArguments() != null ? getArguments().getInt("num") : 1;
        mModelFrom = getHolderActivity().getIntent().getIntExtra(PAPER_FROM,0);
        currentSmallViewPage = 0;
    }

    @Override
    protected void updateViews(boolean isShowLoading) {
//        if(getQuesType(mNum).equals("作文")||
//                getQuesType(mNum).equals("看图写句子")||
//                getQuesType(mNum).equals("翻译题")){
//            showCommonTesePaper(false);
//        }else if(getQuesType(mNum).equals("词汇填空")||
//                getQuesType(mNum).equals("阅读填空")||
//                getQuesType(mNum).equals("句子填空")||
//                getQuesType(mNum).equals("翻译填空")||
//                getQuesType(mNum).equals("短文填空")||
//                getQuesType(mNum).equals("听力填空")){
//            showCommonTesePaper(true);
//        }else if(getQuesType(mNum).equals("听力选择")||
//                getQuesType(mNum).equals("阅读选择")||
//                getQuesType(mNum).equals("阅读判断")||
//                getQuesType(mNum).equals("完形选择")){
//            showCommonTesePaper(true);
//        }else if(getQuesType(mNum).equals("单选题")){
//            showCommonTesePaper(false);
//        }else if(getQuesType(mNum).equals("阅读简答")||
//                getQuesType(mNum).equals("听力简答")){
//            showCommonTesePaper(true);
//        }else if(getQuesType(mNum).equals("阅读理解")||
//                getQuesType(mNum).equals("匹配题")){
//            showCommonTesePaper(true);
//        }else if(getQuesType(mNum).equals("改错题")){
//            showCommonTesePaper(true);
//        }

        if(getQuesType(mNum).equals("作文")||
                getQuesType(mNum).equals("看图写句子")||
                getQuesType(mNum).equals("翻译题")||
                getQuesType(mNum).equals("单选题")||
                getQuesType(mNum).equals("语音表达")){
            VpAnswer.setVisibility(View.GONE);
            showCommonTesePaper(false);
        }else{
            VpAnswer.setVisibility(View.VISIBLE);
            showCommonTesePaper(true);
        }

        relContainer.post(new Runnable() {
            @Override
            public void run() {
                mFlLoading.setVisibility(View.GONE);
                if (layoutId == R.layout.paper_zgt||layoutId == R.layout.paper_dxt) {
                    DialogHelper.showGuideOne(getHolderActivity());
                    // DialogHelper.showPopup(GuessTestingPaperFragment.this);
                }else{
                    DialogHelper.showGuideTwo(getHolderActivity());
                }
            }
        });

    }

    @Override
    public int attachLayoutRes() {
        return R.layout.znbk_paper_commonly;
//        if(getQuesType(mNum).equals("作文")||
//                getQuesType(mNum).equals("翻译题")||
//                getQuesType(mNum).equals("看图写句子")){
//            layoutId = R.layout.znbk_paper_zw;
//        }else if(getQuesType(mNum).equals("词汇填空")||
//                getQuesType(mNum).equals("改错题")||
//                getQuesType(mNum).equals("阅读填空")||
//                getQuesType(mNum).equals("句子填空")||
//                getQuesType(mNum).equals("翻译填空")||
//                getQuesType(mNum).equals("短文填空")||
//                getQuesType(mNum).equals("听力填空")){
//            layoutId =  R.layout.znbk_paper_tkt;
//        }else if(getQuesType(mNum).equals("单选题")){
//            layoutId =  R.layout.znbk_paper_dxt;
//        }else if(getQuesType(mNum).equals("听力选择")||
//                getQuesType(mNum).equals("匹配题")||
//                getQuesType(mNum).equals("阅读理解")||
//                getQuesType(mNum).equals("完形选择")||
//                getQuesType(mNum).equals("阅读选择")||
//                getQuesType(mNum).equals("阅读判断")){
//            layoutId =  R.layout.znbk_paper_xzt;
//        }else if(getQuesType(mNum).equals("阅读简答")||
//                getQuesType(mNum).equals("听力简答")){
//            layoutId =  R.layout.znbk_paper_ydjd;
//        }
//
//        return layoutId;
    }


    @Override
    public void initViews(View view, Bundle savedInstanceState) {
        state = mEntityRdqh.getModelSinglePaperInfo().getModelPaperInfo().getAnswerState();
        Log.e("===111111===888888==", String.valueOf(state));
        mFlLoading = (FrameLayout) view.findViewById(R.id.fl_ques_loading);
        relContainer = (View) view.findViewById(R.id.common_main);
        LayoutSelfRate = (LinearLayout) view.findViewById(R.id.layout_self_rate);
        TvContentType = (TextView) view.findViewById(R.id.textview_content_type);
        TvContentNumber = (TextView) view.findViewById(R.id.textview_content_number);
        LvContent = (BounceListView) view.findViewById(R.id.listview_content);
        VpAnswer = (ViewPager) view.findViewById(R.id.viewpage_answer);

        /*
        * 题目简介(试题)
        * */
        TvContentType.setText(mEntityRdqh.getModelSinglePaperInfo().getModelPaperInfo().getPaperName());
        /*
        * 匹配题目小题数分布
        * */
        TvContentNumber.setText(Html.fromHtml("<font color='#3399cc'>"+(mNum+1)+"</font>"+"/"+"<font color='#686868'>"+getQusSum()+"</font>"));

        /*
        *笔记相关
        * */
        mTvTypeName = (TextView) view.findViewById(R.id.tv_typeName);
        String GenreName = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(mNum).getGenreName();
        String TypeName = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(mNum).getTypeName();
        if(!GenreName.equals("")){
            TypeName = GenreName;
        }
//        double score =  mEntityRdqh.getModelSinglePaperInfo().getModelPaperInfo().getDetail().get(mNum).getScore();
//        mTvTypeName.setText(TypeName + " (" + score + "分)");
        mTvTypeName.setText(TypeName);

        mCivNote = (ClickImageView) view.findViewById(R.id.civ_note);
        mCivAccessToCounselling = (ClickImageView) view.findViewById(R.id.civ_accessToCounselling);
        mCivAccessToCounselling.setClickListener(new ClickImageView.ClickListener() {
            @Override
            public void onClick() {


                List<WrongTopicTutoringModelEntity.StuAnswerBean> jsonAnswerList
                        = new ArrayList<WrongTopicTutoringModelEntity.StuAnswerBean>();

                int TotalItemCount = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(mNum).getTotalItemCount();
                int QuesItemSize = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(mNum).getChildList().size();
                if(TotalItemCount==QuesItemSize){

                    for(int i=0;i<ZnbkPaperInfor.TotalItemCount;i++){

                        List<WrongTopicTutoringModelEntity.StuAnswerBean.SubChildListBean> jsonSubChildList
                                = new ArrayList<WrongTopicTutoringModelEntity.StuAnswerBean.SubChildListBean>();

                        String StuAssess = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(mNum).
                                getChildList().get(i).getSubChildList().get(0).getSubChildStuAssess();
                        String StuAnswer = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(mNum).
                                getChildList().get(i).getSubChildList().get(0).getSubChildStuAnswer();
                        String UpLoadPath = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(mNum).
                                getChildList().get(0).getSubChildList().get(0).getUpLoadPath();
                        jsonSubChildList.add(WrongTopicTutoringModel.getSubChildListBean(StuAssess,1,StuAnswer,UpLoadPath));
                        jsonAnswerList.add(WrongTopicTutoringModel.getStuAnswerBean(i+1,jsonSubChildList));
                        ZnbkPaperInfor.ListStuAnswerCtfd = jsonAnswerList;
                    }

                }else if(TotalItemCount>QuesItemSize){
                    List<WrongTopicTutoringModelEntity.StuAnswerBean.SubChildListBean> jsonSubChildList
                            = new ArrayList<WrongTopicTutoringModelEntity.StuAnswerBean.SubChildListBean>();

                    String StuAssess = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(mNum).
                            getChildList().get(0).getSubChildList().get(0).getSubChildStuAssess();
                    String StuAnswer = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(mNum).
                            getChildList().get(0).getSubChildList().get(0).getSubChildStuAnswer();
                    String UpLoadPath = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(mNum).
                            getChildList().get(0).getSubChildList().get(0).getUpLoadPath();
                    jsonSubChildList.add(WrongTopicTutoringModel.getSubChildListBean(StuAssess,1,StuAnswer,UpLoadPath));
                    jsonAnswerList.add(WrongTopicTutoringModel.getStuAnswerBean(1,jsonSubChildList));
                }

                String QuesID = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(mNum).getQuesID();
                String CreatTime = mEntityRdqh.getModelSinglePaperInfo().getModelPaperInfo().getCreateTime();

                WrongTopicTutoringPaperActivity.launch(getHolderActivity(),QuesID,CreatTime,jsonAnswerList,ZnbkPaperDef.FROM_WRONG_TOPIC_TUTORING);
            }
        });
        mCivKnowledgePoint = (ClickImageView) view.findViewById(R.id.civ_knowledgePoint);

        if(mEntityRdqh.getModelSinglePaperInfo().getModelPaperInfo().getAnswerState()==3){
            if(mEntityRdqh.getModelItemAnswerDetailList().get(mNum).getCorrectRate()<0.6){
                mCivAccessToCounselling.setVisibility(View.VISIBLE);
            }else{
                mCivAccessToCounselling.setVisibility(View.GONE);
            }
        }else{
            mCivAccessToCounselling.setVisibility(View.GONE);
        }
        mCivKnowledgePoint.setVisibility(View.GONE);
        mCivNote.setVisibility(View.VISIBLE);


        if (!mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(mNum).getNoteId().equals("")) {
            //获取已有学生笔记内容,显示查看图标
            IsHaveNoteRdqh = true;
        } else {
            //显示写入笔记图标
            IsHaveNoteRdqh = false;
        }

        final String NoteID = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(mNum).getNoteId();
        String ResType = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(mNum).getResType();
        final String TypeNo = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(mNum).getTypeNo();
        final String Title = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(mNum).getQuesBrief();
        final String QuesID = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(mNum).getQuesID();
        int NoteFlag= -1;

        if (ResType.equals("Q")) {
            NoteFlag = 0;
            ResType = TypeNo;
        } else {
            NoteFlag = 1;
        }

        if (IsHaveNoteRdqh) {
            //获取已有学生笔记内容,显示查看图标
            mCivNote.setBackgroundResource(R.mipmap.znbk_button_check_notes);
        } else {
            //显示写入笔记图标
            mCivNote.setBackgroundResource(R.mipmap.znbk_button_no_notes);
        }

        final int finalNoteFlag = NoteFlag;
        final String finalResType = ResType;
        mCivNote.setClickListener(new ClickImageView.ClickListener() {
            @Override
            public void onClick() {
                getNotesData(QuesID, finalNoteFlag);
            }
        });

    }

    @Override
    public void onResume() {
        super.onResume();
        if(mNum==WeekAscensionPaperActivity.currentBigViewPage) {
            if (IsHaveNoteRdqh) {
                //获取已有学生笔记内容,显示查看图标
                mCivNote.setBackgroundResource(R.mipmap.znbk_button_check_notes);
            } else {
                //显示写入笔记图标
                mCivNote.setBackgroundResource(R.mipmap.znbk_button_no_notes);
            }
        }
    }

    /*
            * @@显示试卷主体
            * 实现试卷界面的布局展示
            * */
    private void showCommonTesePaper(boolean bShowChildViewPager){

         /*
        * 试题主干显示区
        * */
        if(getQuesType(mNum).equals("作文")||
                getQuesType(mNum).equals("看图写句子")||
                getQuesType(mNum).equals("翻译题")||
                getQuesType(mNum).equals("语音表达")){
            mAdapter = new ZnbkContentZwAdapter(getActivity(), 1, mNum,mModelFrom);
        }else if(getQuesType(mNum).equals("听力选择")||
                getQuesType(mNum).equals("听力填空")||
                getQuesType(mNum).equals("听力简答")){
//            mAdapter = new ZnbkContentTlxzAdapter(getActivity(),1,mNum,mModelFrom);
        }else if(getQuesType(mNum).equals("单选题")) {
            mAdapter = new ZnbkContentDxtAdapter(getActivity(), 1, mNum,mModelFrom);
        }else if(getQuesType(mNum).equals("阅读理解")||
                getQuesType(mNum).equals("完形选择")||
                getQuesType(mNum).equals("阅读选择")||
                getQuesType(mNum).equals("阅读判断")||
                getQuesType(mNum).equals("阅读简答")){
            mAdapter = new ZnbkContentXztAdapter(getActivity(),1,mNum,mModelFrom);
        }else if(getQuesType(mNum).equals("改错题")||
                getQuesType(mNum).equals("词汇填空")||
                getQuesType(mNum).equals("阅读填空")||
                getQuesType(mNum).equals("句子填空")||
                getQuesType(mNum).equals("翻译填空")||
                getQuesType(mNum).equals("短文填空")||
                getQuesType(mNum).equals("默写题")){
            mAdapter = new ZnbkContentTktAdapter(getActivity(),1,mNum,mModelFrom);
        }else if(getQuesType(mNum).equals("匹配题")){
            mAdapter = new ZnbkContentPptAdapter(getActivity(),1,mNum,mModelFrom);
        }
        LvContent.setAdapter(mAdapter);
        LvContent.setPadding(0,0,0,0);

        if(bShowChildViewPager) {

//            /*
//            *答题区小题数量
//            * */
//            TvAnswerAmount.setText("本题包含"+getSubjectSum(mNum)+"个小题");
            /*
            * 答题区
            * */
            list = new ArrayList<View>();
            list.clear();
            int sumSubject = getChildCount(mNum);
            for (int k = 0; k < sumSubject; k++) {

                BounceListView LvAnswer = new BounceListView(getActivity());
                if(getQuesType(mNum).equals("听力简答")||
                        getQuesType(mNum).equals("阅读简答")){
//                    LvAnswer.setAdapter(new ZnbkResponseTljdAdapter(getActivity(),1,mNum,k,mModelFrom));
                }else if(getQuesType(mNum).equals("阅读理解")||
                        getQuesType(mNum).equals("完形选择")||
                        getQuesType(mNum).equals("听力选择")){
                    LvAnswer.setAdapter(new ZnbkResponseXztAdapter(getActivity(),1,mNum,k,mModelFrom));
                }else if(getQuesType(mNum).equals("短文填空")||
                        getQuesType(mNum).equals("听力填空")||
                        getQuesType(mNum).equals("翻译填空")||
                        getQuesType(mNum).equals("句子填空")||
                        getQuesType(mNum).equals("阅读填空")||
                        getQuesType(mNum).equals("词汇填空")||
                        getQuesType(mNum).equals("改错题")||
                        getQuesType(mNum).equals("默写题")){
                    LvAnswer.setAdapter(new ZnbkResponseTktAdapter(getActivity(),1,mNum,k,mModelFrom));
                }else if(getQuesType(mNum).equals("匹配题")){
                    LvAnswer.setAdapter(new ZnbkResponsePptAdapter(getActivity(),1,mNum,k,mModelFrom));
                }
                /*
                *答题区小题数量
                * */
                list.add(LvAnswer);
            }

            VpAnswer.setAdapter(new AnswerViewPagerAdapter(list));
            VpAnswer.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }

                @Override
                public void onPageSelected(int position) {
                    //此处添加父页面操作事件
                    currentSmallViewPage = position;
                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });
        }


    }


    /*
    *获取题型
    * */
      /*
    *获取题型
    * f：作文  大Z：听力简答  大S：听力填空  E：听力选择  大X：阅读简答  D：阅读选择  K：阅读判断  Q：阅读填空
    * m：匹配题  大C：完形选择  大O：句子填空   g：翻译题   d：看图写句子  A；单选题
    * N:词汇填空
    * */
    private String getQuesType(int postion){
        return   mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(postion).getTypeName();
    }

    /*
    * 获取试卷总页数
    * */
    private int getQusSum(){
        return mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().size();
    }

    /*
    * 获取题目对应的小题数目(显示页数)
    * */
    private int getChildCount(int postion){
        int sumChildItem = -1;
        int childItemCount = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(postion).getChildList().size();
        int totalItemCount = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(postion).getTotalItemCount();
        if(totalItemCount==childItemCount||getQuesType(postion).equals("匹配题")){
            sumChildItem = totalItemCount;
        }else{
            sumChildItem = 1;
        }
        return sumChildItem;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (!isVisibleToUser && mAdapter != null){//可见时进行调用
            mAdapter.pause();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mAdapter != null){//不可见 暂停音乐播放
            mAdapter.pause();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mAdapter != null){//不可见 暂停音乐播放
            mAdapter.pause();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mAdapter != null) {
            mAdapter.stop();

        }
    }

    /*****************************************************************************************************/
    /***查看笔记内容*******/
    PopupWindow popWinNotes = null;
    TextView TvNotes;
    ScaleButton SBtnChangeNotes;
    public PopupWindow showNotesPopupWindow(final View anchorView, final String noteContent,final String noteID) {
        final View contentView = LayoutInflater.from(anchorView.getContext()).inflate(R.layout.znbk_pw_notes, null);
        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        // 创建PopupWindow时候指定高宽时showAsDropDown能够自适应
        // 如果设置为wrap_content,showAsDropDown会认为下面空间一直很充足（我以认为这个Google的bug）
        // 备注如果PopupWindow里面有ListView,ScrollView时，一定要动态设置PopupWindow的大小
        popWinNotes = new PopupWindow(contentView,
                contentView.getMeasuredWidth(), contentView.getMeasuredHeight(), false);

        TvNotes = (TextView) contentView.findViewById(R.id.tv_notes);
        TvNotes.setText(noteContent);

        SBtnChangeNotes = (ScaleButton) contentView.findViewById(R.id.sbtn_change_notes);
        SBtnChangeNotes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWinNotes.dismiss();

                String Title = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(mNum).getQuesBrief();
                String ResType = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(mNum).getResType();
                String TypeNo = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(mNum).getTypeNo();
                String QuesID = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(mNum).getQuesID();
                if (ResType.equals("Q")) {
                    ResType = TypeNo;
                }


                NoteDetailActivity.launch(getHolderActivity(),noteContent,Title,noteID,ResType,QuesID,
                        ZnbkPaperDef.FROM_WEEK_ASCENSION);


            }
        });

        popWinNotes = new PopupWindow(contentView,
                FrameLayout.LayoutParams.MATCH_PARENT, contentView.getMeasuredHeight(), false);

        contentView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                // 自动调整箭头的位置
                autoAdjustArrowPos(popWinNotes, contentView, anchorView);
                contentView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
        });
        // 如果不设置PopupWindow的背景，有些版本就会出现一个问题：无论是点击外部区域还是Back键都无法dismiss弹框
        popWinNotes.setBackgroundDrawable(new ColorDrawable());

        // setOutsideTouchable设置生效的前提是setTouchable(true)和setFocusable(false)
        popWinNotes.setOutsideTouchable(true);

        // 设置为true之后，PopupWindow内容区域 才可以响应点击事件
        popWinNotes.setTouchable(true);

        // true时，点击返回键先消失 PopupWindow
        // 但是设置为true时setOutsideTouchable，setTouchable方法就失效了（点击外部不消失，内容区域也不响应事件）
        // false时PopupWindow不处理返回键
        popWinNotes.setFocusable(true);
//        popWinNotes.setTouchInterceptor(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                return false;   // 这里面拦截不到返回键
//            }
//        });
        // 如果希望showAsDropDown方法能够在下面空间不足时自动在anchorView的上面弹出
        // 必须在创建PopupWindow的时候指定高度，不能用wrap_content
        popWinNotes.showAsDropDown(anchorView);


        return popWinNotes;
    }

    /*****fast-json 解析笔记内容******/
    private void getNotesData(String QuesID,int NoteFlag){

        String url = ZnbkPaperInfor.BaseHttpAdress+"api/ZNBK/W_ZNBK_GetPersonalNote?"+"StuID="+ UserInfo.StuId+
                "&SubjectID="+UserInfo.SubjectId+"&StageNo="+UserInfo.StageNo+"&QuesID="+QuesID+
                "&IsReplace=true"+"&Flag="+NoteFlag;

        StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String arg0) {
                Log.e("==wgl==",""+arg0);//获取完成后，在 http://www.bejson.com/ 解析查看数据
                dealData(arg0);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError arg0) {
                // TODO Auto-generated method stub
                String ResType = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(mNum).getResType();
                String TypeNo = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(mNum).getTypeNo();
                final String Title = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(mNum).getQuesBrief();
                final String QuesID = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(mNum).getQuesID();
                if (ResType.equals("Q")) {
                    ResType = TypeNo;
                }
                NoteDetailActivity.launch(getHolderActivity(),"",Title,"", ResType,QuesID,
                            ZnbkPaperDef.FROM_WEEK_ASCENSION);
            }
        });
        new Volley().newRequestQueue(getContext()).add(request);
    }


    //处理数据
    private void dealData(String result){
        Gson gson = new Gson();
        NotePaperEntity notePaperEntity = gson.fromJson(result, NotePaperEntity.class); // data 转实体
        String NoteContent = notePaperEntity.getModelNoteList().getContent();
        String NoteID = notePaperEntity.getModelNoteList().getNoteID();

        if(!NoteContent.equals("")) {
            showNotesPopupWindow(mCivNote,NoteContent,NoteID);
        }

    }

    private void autoAdjustArrowPos(PopupWindow popupWindow, View contentView, View anchorView) {
        View upArrow = contentView.findViewById(R.id.up_arrow);
        View downArrow = contentView.findViewById(R.id.down_arrow);

        int pos[] = new int[2];
        contentView.getLocationOnScreen(pos);
        int popLeftPos = pos[0];
        anchorView.getLocationOnScreen(pos);
        int anchorLeftPos = pos[0];
        int arrowLeftMargin = anchorLeftPos - popLeftPos + anchorView.getWidth() / 2 - upArrow.getWidth() / 2;
        upArrow.setVisibility(popupWindow.isAboveAnchor() ? View.INVISIBLE : View.VISIBLE);
        downArrow.setVisibility(popupWindow.isAboveAnchor() ? View.VISIBLE : View.INVISIBLE);

        RelativeLayout.LayoutParams upArrowParams = (RelativeLayout.LayoutParams) upArrow.getLayoutParams();
        upArrowParams.leftMargin = arrowLeftMargin;
        RelativeLayout.LayoutParams downArrowParams = (RelativeLayout.LayoutParams) downArrow.getLayoutParams();
        downArrowParams.leftMargin = arrowLeftMargin;
    }

/**************************************************************************************************************************/

}